<?php
namespace GuessFatherSong\Controller;
use Common\Controller\GuessFatherSongController;

class ActivityController extends GuessFatherSongController {

    const AppID     =   'wx514169f146f962d6';       //wx370386b7eb0c04bc
    const AppSecret =   '69e9708ac8a179f59f839d67d5331f48'; //25d7798f008b06ec3641d5e709599600

    public function __construct()
    {
        $sessionid = 'PHPSESSID='.$this->getSessionId();

        $getsessionid = $_SERVER['HTTP_COOKIE'];
        if ($sessionid!=$getsessionid){
            $this->returnData('','状态已过期请重新授权',400);
        }
    }

    /**
     * 获取题目
     */
    public function new_problem()
    {
        $uid        =   I('post.uid','','htmlspecialchars');
        $share_uid  =   I('post.share_uid','','htmlspecialchars');

        if (! empty($uid))
        {
            $where          =   array();
            $data           =   array();
            $where['uid']   =   $uid;
            $field          =   array('uid','nickname','avatarurl','openid','session_key','game_num','totle_num','activity_time','activity_num','activity_chance');
            $member_data    =   M('fathersong_member')->where($where)->field($field)->find();

            if (! empty($member_data))
            {
                //绑定好友
                if (! empty( $share_uid) &&  $share_uid != $uid)
                {
                    $this->share_fraend($share_uid,$uid);
                }

                $today_time     =   strtotime(date('Y-m-d'));
                //限制用户一天玩的次数
                if ($member_data['activity_time'] >= $today_time && $member_data['activity_chance'] == 0)
                {
                    $this->returnData($data,$msg='挑战机会已用完,请分享获得机会',$code=400);
                }

                if ($member_data['activity_chance'] > 0 || ($member_data['activity_time'] < $today_time) )
                {
                    //减去一次机会
                    $update_data                =   array();
                    if($member_data['activity_time'] > $today_time)
                    {
                        $update_data['activity_time']   =   time();
                        $update_data['activity_num']    =   $member_data['activity_num']    +   1;
                        $update_data['activity_chance'] =   $member_data['activity_chance']    -   1;
                    }
                    else
                    {
                        $update_data['activity_time']   =   time();
                        $update_data['activity_chance'] =   0;
                        $update_data['activity_num']    =   1;
                    }

                    M('fathersong_member')->where($where)->save($update_data);

                    $data['question']           =   $this->geta_ctivity_quersion($member_data,1,20);
                    $data['success_number']     =   count($data['question']);
                    $this->returnData($data,$msg='ok',$code=200);
                }
                else
                {
                    $this->returnData($data,$msg='你已经用完机会了',$code=400);
                }
            }
        }

        $this->returnData($data,$msg='用户id参数不能为空',$code=404);
    }

    /**
     * 回答
     */
    public function new_answer()
    {
        $id         =   I('post.id','','htmlspecialchars');
        $number     =   I('post.number','','htmlspecialchars');
        $aswer_id   =   I('post.aswer_id','','htmlspecialchars');
        $uid        =   I('post.uid','','htmlspecialchars');
        $answer_tg  =   I('post.answer_tg','','htmlspecialchars');
        $lastTime   =   I('post.lastTime','','htmlspecialchars');
        $data       =   array();
        if (! empty($uid) && ! empty($number)
        && ! empty($aswer_id) && ! empty($uid))
        {
            $where          =   array();
            $where['uid']   =   $uid;
            $field          =   array('uid','money_total','openid','prize_num','total_money');
            $member_data    =   M('fathersong_member')->where($where)->field($field)->find();

            if (! empty($member_data))
            {
                $question_data  =   S('fathersong_questions');
                if (! empty($question_data))
                {
                    $this->cachequesion(3600*24*30);
                    $question_data  =   S('fathersong_questions');
                }

                $target_question    =   $question_data[$id];

                if (! empty($target_question))
                {
                    if (! empty($answer_tg))
                    {
                        //答对的做验证
                        $where_record           =   array();
                        $field                  =   array('id','create_time','answer');
                        $where_record['uid']    =   $uid;
                        $where_record['status'] =   0;
                        $where_record['type']   =   1;  //1 端午节活动日结，2端午后周结
                        $questions_record       =   M('fathersong_activity_record')->where($where_record)->field($field)->find();
                        if (! empty($questions_record))
                        {
                            $answer_list            =   explode('|',$questions_record['answer']);
                            $pay_status             =   true;

                            foreach ($answer_tg as $key=> $val)
                            {
                                if($answer_list[$key] != $val)
                                {
                                    $pay_status     =   false;
                                }
                            }

                            if ($pay_status)
                            {
                                //更新活动记录
                                $where_record                   =   array();
                                $where_record['uid']            =   $uid;
                                $where_record['id']             =   $questions_record['id'];

                                $update_record                  =   array();
                                $update_record['update_time']   =   time();
                                $update_record['status']        =   1;
                                $update_record['time']          =   $update_record['update_time'] - $questions_record['create_time'];
                                $update_record['right_num']     =   count($answer_tg);
                                $update_record['service_time']  =   $update_record['update_time'] - $questions_record['create_time'];
                                M('fathersong_activity_record')->where($where_record)->save($update_record);

                                $where_record                   =   array();
                                $where_record['uid']            =   $uid;
                                $where_record['status']         =   1;

                                $data['max_record']     =  M('fathersong_activity_record')->where($where_record)->min('time');
                                $data['now_record']     =  $lastTime;
                                $data['msg']            =   '恭喜你通过所有关卡';
                                $data['type']           =   4;
                                $this->returnData($data,$msg='恭喜你通过所有关卡',$code=200);
                            }
                            else
                            {
                                //发错的
                                $data['challenge_id']   =   0;
                                $data['msg']            =   '回答错误';
                                $data['number']         =   $number;
                                $data['type']           =   2;
                                $this->returnData($data,$msg='回答错误',$code=200);
                            }
                        }
                        else
                        {
                            //发错的
                            $data['challenge_id']   =   0;
                            $data['msg']            =   '非法操作';
                            $data['number']         =   $number;
                            $data['type']           =   2;
                            $this->returnData($data,$msg='非法操作',$code=200);
                        }
                    }
                    else
                    {
                        //发错的
                        $data['challenge_id']   =   0;
                        $data['msg']            =   '回答错误';
                        $data['number']         =   $number;
                        $data['type']           =   2;
                        $this->returnData($data,$msg='回答错误',$code=200);
                    }
                }
                else
                {
                    $this->returnData($data,$msg='题目不存在',$code=404);
                }
            }

        }

        $this->returnData($data,$msg='用户id参数不能为空',$code=404);
    }

    /**
     * 规则
     */
    public function rules()
    {
        $data   =   array();
        //$data   =   M('newsong_rule')->find();
        $data[] =   '1、每天赠送1次挑战机会，分享到不同的群可获得更多挑战机会';
        $data[] =   '2、每轮挑战共5关，连续答对则挑战成功，可以获得现金红包一个，金额随机。';
        $data[] =   '3、每轮挑战赢取的现金红包可根据提示直接提现到微信零钱，祝君中红包大奖。';
        $data[] =   '4、本猜歌游戏规则解释权归游戏开发者所有，如需更多咨询，请联系客服。';
        $this->returnData($data,$msg='规则',$code=200);
    }

    /**
     * 分享群
     */
    public function get_numbers()
    {
        $data       =   array();
        $uid        =   I('post.uid','','htmlspecialchars');
        $endata     =   I('post.endata','','htmlspecialchars');
        $n          =   I('post.n','','htmlspecialchars');
        $vi         =   I('post.vi','','htmlspecialchars');
        $activity   =   I('post.activity','','htmlspecialchars');   //1表示复活，空表示机会

        if (! empty($endata) && ! empty($uid) && ! empty($vi))
        {
            $where          =   array();
            $where['uid']   =   $uid;
            $field          =   array('uid','openid','session_key','game_num','login_num','activity_chance');
            $member_data    =   M('fathersong_member')->where($where)->field($field)->find();

            if (! empty($member_data))
            {
                //登陆次数
                if(! empty($n))
                {
                    $update_member                  =   array();
                    $update_member['update_time']   =   time();
                    $update_member['login_num']     =   $member_data['login_num']    +   1;
                    M('fathersong_member')->where($where)->save($update_member);
                }

                //解析openGId
                $openGId = $this->getopenGId(self::AppID, $member_data['session_key'], $endata, $vi);

                if ($openGId == -1)
                {
                    $log            =   array();
                    $log['module']  =   'New';
                    $log['log']     =   $openGId;
                    $log['create_time'] =   time();
                    M('yao_log')->add($log);
                }

                if ($openGId != -1)
                {
                    //创建群
                    $where_group                =   array();
                    $where_group['uid']         =   $uid;
                    $where_group['opengid']     =   $openGId;
                    $where_group['sharetime']   =   date('Y-m-d');
                    $field                      =   array('id','opengid','sharenum','sharetime');
                    $group_data                 =   M('fathersong_activity_group')->where($where_group)->field($field)->find();
                    if (! empty($group_data))
                    {
                        $update_data                =   array();
                        $update_data['sharenum']    =   $group_data['sharenum'] +   1;
                        M('fathersong_activity_group')->where($where_group)->save($update_data);
                        $this->returnData($data,$msg='本群已分享过',$code=400);
                    }
                    else
                    {
                        $insert_data                =   array();
                        $insert_data['opengid']     =   $openGId;
                        $insert_data['uid']         =   $uid;
                        $insert_data['sharetime']   =   date('Y-m-d');
                        $insert_data['sharenum']    =   1;
                        $insert_data['create_time'] =   time();
                        $result     =   M('fathersong_activity_group')->add($insert_data);

                        if (! empty($result))
                        {
                            if (empty($activity))
                            {
                                //加机会
                                $where                              =   array();
                                $where['uid']                       =   $uid;
                                $update_member                      =   array();
                                $update_member['update_time']       =   time();
                                $update_member['activity_time']     =   time();
                                $update_member['activity_chance']   =   $member_data['activity_chance'] + 1;
                                $result     =   M('fathersong_member')->where($where)->save($update_member);
                            }

                            if (! empty($result))
                            {
                                $data['msg']    =   '分享成功';
                                $this->returnData($data,$msg='分享成功',$code=200);
                            }
                        }
                    }
                }
            }
        }

        $this->returnData($data,$msg='分享失败',$code=400);
    }

    /**
     * 获取机会
     */
    public function prize_num()
    {
        $uid        =   I('post.uid','','htmlspecialchars');
        if (! empty($uid))
        {
            $where          =   array();
            $data           =   array();
            $where['uid']   =   $uid;
            $field          =   array('uid','game_num','totle_num','prize_num','money_total','activity_time','play_num','activity_chance');
            $member_data    =   M('fathersong_member')->where($where)->field($field)->find();

            if (! empty($member_data))
            {
                $today_time     =   strtotime(date('Y-m-d'));
                //限制用户一天玩的次数
                if ($member_data['activity_time'] > $today_time && $member_data['activity_chance'] == 0)
                {
                    $data['game_num']   =   $member_data['activity_chance'];
                    $data['totle_num']  =   $member_data['totle_num'];
                    $data['money_total']=   $member_data['money_total'];
                    $data['prize_num']  =   $member_data['prize_num'];
                    $this->returnData($data,$msg='机会已用完,分享群获得机会',$code=400);
                }

                $data['game_num']   =   1;

                if(empty($member_data['activity_chance']) && $member_data['activity_time'] < $today_time)
                {
                    $data['game_num']   =   1;
                }

                $data['totle_num']  =   $member_data['totle_num'];
                $data['money_total']=   $member_data['money_total'];
                $data['prize_num']  =   $member_data['prize_num'];
                $this->returnData($data,$msg='OK',$code=200);
            }
        }

        $this->returnData($data,$msg='用户id参数不能为空',$code=404);
    }

    /**
     * 排行榜
     */
    public function ranking()
    {
        $data       =   array();
        $uid        =   I('post.uid','','htmlspecialchars');
        $today_time             =   strtotime(date('Y-m-d'));
        $where                  =   array();
        $where['create_time']   =   array('EGT',$today_time);
        $where['status']        =   1;
        $data   =   M('fathersong_activity_record')->where($where)->field("min(time) as time,nickname,avatarurl")->group('uid')->order(array('time'=>'asc'))->select();
        $this->returnData($data,$msg='ok',$code=200);
    }

    public function win_list()
    {
        $data       =   array();
        $uid        =   I('post.uid','','htmlspecialchars');
        $date1 = '2018-06-15';
        $date2 = '2018-06-16';
        $date3 = '2018-06-17';
        $date4 = '2018-06-18';

        $data[0] = $this->getrank($date1);
        $data[1] = $this->getrank($date2);
        $data[2] = $this->getrank($date3);
        $data[4] = $this->getrank($date4);
        $msg['tabName_1']  =   '今日排行';
        $msg['tabName_2']  =   '端午期间每天发现金';
        $this->returnData($data,$msg,$code=200);
    }

    private function getrank($date)
    {
        $to_time        =   strtotime($date);
        $end_time       =   strtotime($date.' 23:59:59');
        $data           =   array();
        $where          =   array();
        $where['date']  =   $date;
        $where['status']=   1;
        $data_record  =   M('fathersong_activity_record')->where($where)->field("min(time) as time,nickname,avatarurl,win_money,create_time")->group('uid')->order(array('time'=>'asc'))->limit(3)->select();

        $money_list     =   array(200,100,50);

        for ($i=0;$i<=2;$i++)
        {
            $data[$i]['date']       =   date('m-d',$to_time);
            $data[$i]['time']       =   '未知';
            $data[$i]['nickname']   =   '虚位以待';
            $data[$i]['avatarurl']  =   'http://oss.beikg.cn/guessnewsong/logo.png';
            $data[$i]['win_money']  =   $money_list[$i];
            $data[$i]['giftname']   =   '获得奖金'.$money_list[$i] .'元';
        }

        if ($data_record && time() >= $end_time)
        {
            $n              =   0;
            foreach ($data_record as $key=> $val)
            {
                $data[$key]             =   $val;
                $data[$key]['date']     =   date('m-d',$to_time);
                $data[$key]['giftname'] =   '获得奖金'.$money_list[$n] .'元';
                $data[$key]['win_money']=   $money_list[$n];
                $n++;
            }
        }
        return $data;
    }

    /**
     * 练习模式
     */
    public function practice()
    {
        $uid        =   I('post.uid','','htmlspecialchars');
        if (! empty($uid))
        {
            $data['question']           =   $this->practice_question($uid, $num = 20);
            $data['success_number']     =   count($data['question']);
            $this->returnData($data,$msg='ok',$code=200);
        }
    }

    /**
     * 分享模板
     */
    public function sharetem(){

        $imgsrc[] = $this->url.'share/newsongshares.jpg';
        $imgsrc[] = $this->url.'share/newsongshare2.jpg';

        $data = array(
            'title'=>'端午三天！千元大奖等你来拿！', //这是什么歌？猜对领红包
            'imgsrc'=>$imgsrc[array_rand($imgsrc)],
        );

        $this->returnData($data);
    }

    /**
     * 分享好友
     * @param $share_uid
     * @param $uid
     */
    public function share_fraend($share_uid,$uid)
    {
        $where          =   array();
        $where['uid']   =   $share_uid;
        $field          =   array('uid');
        $member_data    =   M('fathersong_member')->where($where)->field($field)->find();
        if (! empty($member_data))
        {
            $where_relationship                         =   array();
            $where_relationship['my_member_id']         =   $share_uid;
            $where_relationship['coupling_member_id']   =   $uid;
            $field_relationship                         =   array('id');
            $result     =   M('fathersong_relationship')->where($where_relationship)->field($field_relationship)->find();

            if (empty($result))
            {
                $insert_data                        =   array();
                $insert_data['my_member_id']        =   $share_uid;
                $insert_data['coupling_member_id']  =   $uid;
                $insert_data['createtime']          =   time();
                $insert_data['appid']               =   self::AppID;
                M('fathersong_relationship')->add($insert_data);
            }
        }
    }
}